package com.wing.setting.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.order.service.DynamicService;
import com.wing.setting.dao.BusinessClassifySetDao;
import com.wing.setting.model.entity.BusinessClassifySet;
import com.wing.setting.model.request.BusinessClassifySetForm;
import com.wing.setting.model.response.BusinessClassifySetVO;
import com.wing.unit.model.entity.CustomerType;
import com.wing.unit.model.response.CustomerTypeVO;
import com.wing.unit.model.response.NodeDataVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 业务选项分类设置表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class BusinessClassifySetServiceImpl extends ServiceImpl<BusinessClassifySetDao, BusinessClassifySet> implements BusinessClassifySetService {
    private static long ROOT_ID=-1l;
    @Autowired
    private DynamicService dynamicService;
    @Override
    public int add(BusinessClassifySetForm businessClassifySetForm) {

        //校验

        BusinessClassifySet businessClassifySet =new BusinessClassifySet();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(BusinessClassifySet.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(businessClassifySetForm, businessClassifySet, copyOptions);
        if (businessClassifySetForm.getParentId()!=ROOT_ID){
            BusinessClassifySet businessClassifySetParent = new BusinessClassifySet();
            businessClassifySetParent.setId(businessClassifySetForm.getParentId());
            businessClassifySetParent.setHasChild(true);
            if (businessClassifySetForm.getIsDeleted()){
                businessClassifySetParent.setHasEnableChild(true);
            }
            baseMapper.updateById(businessClassifySetParent);
        }

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        String code=dynamicService.getDayNextCode("cab_business_classify_set");
        String day=simpleDateFormat.format(new Date());
        businessClassifySet.setCode("G"+day+code);
        businessClassifySet.setDay(Long.valueOf(day));
        businessClassifySet.setNo(Long.valueOf(code));

        return baseMapper.insert(businessClassifySet);

    }

    @Override
    public List<BusinessClassifySetVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<BusinessClassifySetVO> pageList4app(Page page, Map<String, Object> params) {
        List<BusinessClassifySetVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public BusinessClassifySetVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

   
    @Override
    @Transactional
    public int update(BusinessClassifySetForm businessClassifySetForm) {
        BusinessClassifySetVO businessClassifySetVO = baseMapper.get4appById(businessClassifySetForm.getId());
        if (businessClassifySetVO!=null){
            if (!businessClassifySetVO.getParentId().equals(businessClassifySetForm.getParentId())){
                BusinessClassifySet businessClassifySet = new BusinessClassifySet();
                BeanUtils.copyProperties(businessClassifySetForm,businessClassifySet);
                baseMapper.updateById(businessClassifySet);

                if (businessClassifySetForm.getParentId()!=ROOT_ID){
                    BusinessClassifySet parentBusinessClassifySet = new BusinessClassifySet();
                    parentBusinessClassifySet.setId(businessClassifySetForm.getParentId());
                    parentBusinessClassifySet.setHasChild(true);
                    if (businessClassifySetForm.getIsDeleted()){
                        parentBusinessClassifySet.setHasEnableChild(true);
                    }
                    baseMapper.updateById(parentBusinessClassifySet);
                }
                if (businessClassifySetVO.getParentId()!=ROOT_ID){
                    int count = baseMapper.selectCount(new QueryWrapper<BusinessClassifySet>().eq("parent_id",businessClassifySetVO.getParentId()));
                    if (count==0){
                        BusinessClassifySet businessClassifySetParent = new BusinessClassifySet();
                        businessClassifySetParent.setId(businessClassifySetVO.getParentId());
                        businessClassifySetParent.setHasChild(false);
                        baseMapper.updateById(businessClassifySetParent);
                    }
                    count = baseMapper.selectCount(new QueryWrapper<BusinessClassifySet>().eq("parent_id",businessClassifySetVO.getParentId()).eq("is_deleted",true));
                    if (count==0){
                        BusinessClassifySet businessClassifySetParent = new BusinessClassifySet();
                        businessClassifySetParent.setId(businessClassifySetVO.getParentId());
                        businessClassifySetParent.setHasChild(false);
                        baseMapper.updateById(businessClassifySetParent);
                    }
                }
            }else{
                boolean isUpdateEnable=businessClassifySetVO.getIsDeleted().equals(businessClassifySetForm.getIsDeleted());
                BusinessClassifySet BusinessClassifySet = new BusinessClassifySet();
                BeanUtils.copyProperties(businessClassifySetForm,BusinessClassifySet);
                baseMapper.updateById(BusinessClassifySet);
                if(isUpdateEnable&&!businessClassifySetForm.getIsDeleted()&&businessClassifySetForm.getParentId()!=ROOT_ID){
                    int count = baseMapper.selectCount(new QueryWrapper<BusinessClassifySet>().eq("parent_id",businessClassifySetVO.getParentId()).eq("is_deleted",true));
                    if (count==0){
                        BusinessClassifySet businessClassifySetParent = new BusinessClassifySet();
                        businessClassifySetParent.setId(businessClassifySetVO.getParentId());
                        businessClassifySetParent.setHasChild(false);
                        baseMapper.updateById(businessClassifySetParent);
                    }
                }
            }
        }
        return 0;
    }


    @Override
    @Transactional
    public int enable(Long id) {
        BusinessClassifySetVO businessClassifySetVO = baseMapper.get4appById(id);
        if(businessClassifySetVO!=null){
            BusinessClassifySet businessClassifySet = new BusinessClassifySet();
            businessClassifySet.setId(id);
            businessClassifySet.setIsDeleted(true);
            int updateCount=baseMapper.updateById(businessClassifySet);
            if (businessClassifySetVO.getParentId()!=ROOT_ID){
                BusinessClassifySet businessClassifySetParent = new BusinessClassifySet();
                businessClassifySetParent.setId(businessClassifySetVO.getParentId());
                businessClassifySetParent.setHasEnableChild(true);
                baseMapper.updateById(businessClassifySetParent);
            }
            return updateCount;
        }
        return 0;
    }

    @Override
    public int disable(Long id) {
        BusinessClassifySetVO businessClassifySetVO = baseMapper.get4appById(id);
        if(businessClassifySetVO!=null){
            BusinessClassifySet businessClassifySet = new BusinessClassifySet();
            businessClassifySet.setId(id);
            businessClassifySet.setIsDeleted(false);
            int updateCount=baseMapper.updateById(businessClassifySet);
            if (businessClassifySetVO.getParentId()!=ROOT_ID){
                int count = baseMapper.selectCount(new QueryWrapper<BusinessClassifySet>().eq("parent_id",businessClassifySetVO.getParentId()).eq("is_deleted",true));
                if(count==0){
                    BusinessClassifySet businessClassifySetParent = new BusinessClassifySet();
                    businessClassifySetParent.setId(businessClassifySetVO.getParentId());
                    businessClassifySetParent.setHasEnableChild(false);
                    baseMapper.updateById(businessClassifySetParent);
                }
            }
            return updateCount;
        }
        return 0;
    }

    @Override
    public JsonResult getTreeData(String parentCode) {
        List<BusinessClassifySet> list=baseMapper.selectList(new QueryWrapper<BusinessClassifySet>().eq("code",parentCode));
        if (list.size()==0){
            return JsonResult.success();
        }
        return getTreeData(list.get(0).getId());
    }

    @Override
    public JsonResult getTreeData(Long parentId) {
        List<BusinessClassifySetVO> list = baseMapper.list4app(new HashMap<>());
        Map<Long,List<NodeDataVO>> map=new HashMap<>();
        for (BusinessClassifySetVO typeVO:list){
            if(map.containsKey(typeVO.getParentId())){
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(typeVO.getId().toString());
                nodeDataVO.setName(typeVO.getName());
                nodeDataVO.setCode(typeVO.getCode());
                map.get(typeVO.getParentId()).add(nodeDataVO);
            }else{
                List<NodeDataVO> tmpList=new ArrayList<>();
                NodeDataVO nodeDataVO=new NodeDataVO();
                nodeDataVO.setValue(typeVO.getId().toString());
                nodeDataVO.setName(typeVO.getName());
                nodeDataVO.setCode(typeVO.getCode());
                tmpList.add(nodeDataVO);
                map.put(typeVO.getParentId(),tmpList);
            }
        }
        if (parentId==null){
            parentId=-1l;
        }

        List<NodeDataVO> rootList=map.get(parentId);
        if (rootList==null){
            return JsonResult.success();
        }
        constructTree(rootList,map);
        return JsonResult.success(rootList);
    }

    private void  constructTree(List<NodeDataVO> parentList, Map<Long,List<NodeDataVO>> dataMap){
        for (NodeDataVO node:parentList) {
            Long nodeId=Long.valueOf(node.getValue());
            List<NodeDataVO> childList=dataMap.get(nodeId);
            if (childList!=null){
                node.setChildren(childList);
                constructTree(childList,dataMap);
            }
        }
    }





}
